# -*- coding: utf-8 -*- 
import cherrypy as _cp
from Cheetah.Template import Template 
import pymongo
from pymongo import Connection   
from pymongo.objectid import ObjectId as _id
import pymongo.json_util
import json  
import time
from skeleton import SkeletonView
class MsgView(SkeletonView):   
    @_cp.expose
    def index(self): 
        return self.msgbox(0, 16)
        
        
    @_cp.expose
    def thread(self,tid,page=0,count=16): 
        tid = _id(tid)
        start = page*count
        thread = self.db.threads.find_one({'_id':tid}) 
        cursor = self.db.msgs.find({'tid':tid}).sort('time',pymongo.DESCENDING).skip(start).limit(count)
        msgs = [] 
        for msg in cursor: msgs.append(msg)
        thread['msgs'] = msgs
        new_msg_count = thread['new_msg_count']
        if new_msg_count>0: 
            self.db.msgboxes.update({'uid':thread['uid1']},{'$inc':{'new_msg_count':-new_msg_count}})
        body = str(Template(file='www/msg_thread.html',searchList=[{ 
            'thread':thread,                                                           
        }])) 
        return self.skeleton(body)
            
    @_cp.expose
    def new_msg_count(self,uid): 
        _cp.response.headers['Content-Type'] = 'application/json'
        count = 0
        msgbox = self.db.msgboxes.find_one({'uid':uid},{'new_msg_count':1})
        if msgbox and msgbox.has_key('new_msg_count'):
            count = msgbox['new_msg_count']
        return json.dumps(count)
    
    def create_msgbox(self,uid,uname):
        msgbox = {
            'uid': uid,
            'name': uname,
            'time': time.time(),
            'new_msg_count': 0,
        }
        self.db.msgboxes.save(msgbox)      
    @_cp.expose
    def msgbox(self,page=0,count=16): 
        uid = _cp.session['uid'] 
        start = page*count  
        cursor = self.db.threads.find({'uid1':uid}).sort('updated',pymongo.DESCENDING).skip(start).limit(count)
        threads = []
        for thread in cursor: threads.append(thread)
        body = str(Template(file='www/msgbox.html',searchList=[{
            'uid': _cp.session['uid'],                                                   
            'threads': threads,   
        }])) 
        return self.skeleton(body)  
 
    def msgbox_thread(self,uid1,uid2):
        thread = self.db.threads.find_one({'uid1':uid1,'uid2':uid2})
        if thread: return thread 
        thread = {
            'uid1': uid1,
            'uid2': uid2,
            'time': time.time(),
            'updated': time.time(),
            'new_msg_count': 0,
            'msg_count':0, 
        }
        self.db.threads.save(thread)
        return thread    
        
    def send(self,text,from_uid,to_uid): 
        msg = {
            'text': text,
            'from': from_uid,
            'to': to_uid, 
            'time': time.time(),
        } 
        from_thread = self.msgbox_thread(from_uid, to_uid)
        to_thread = self.msgbox_thread(to_uid,from_uid)
        msgid = self.deliver_msg(from_thread, msg, False)
        self.deliver_msg(to_thread, msg, True)
        
        #return msg of the from_thread
        msg['_id'] = msgid
        return msg    
    
    def deliver_msg(self,thread,msg,is_recv_thread=True):  
        if msg.has_key('_id'): del msg['_id']
        msg['tid'] = thread['_id']
        self.db.msgs.save(msg) 
        if is_recv_thread:
            self.db.threads.update({'_id':thread['_id']},
                                   {'$set':{'updated':time.time()},
                                    '$set':{'latest':msg},
                                    '$inc':{'new_msg_count':1,'msg_count':1}})
            self.db.msgboxes.update({'uid':msg['to']},{'$inc':{'new_msg_count':1}})
        else:
            self.db.threads.update({'_id':thread['_id']},
                                   {'$set':{'updated':time.time()},
                                    '$set':{'latest':msg},
                                    '$inc':{'msg_count':1}})
        return msg['_id']
    

    
    @_cp.expose 
    def send_one(self,text,to_uid):
        from_uid = _cp.session['uid']
        msg = self.send(text, from_uid, to_uid)  
        return str(Template(file='www/blocks/msg.html',searchList=[{
            'msg': msg 
        }])) 
        
    @_cp.expose
    def send_muti(self,text,to_uids=None,to_gids=None):
        _cp.response.headers['Content-Type'] = 'application/json'  
        from_uid = _cp.session['uid']
        res = True
        uids = set()
        if to_uids: 
            to_uids = self.parse_ids(to_uids)
            uids = set(to_uids)
        if to_gids: 
            to_gids = self.parse_ids(to_gids)
            for gid in to_gids:
                uids |= self.group_uids(gid)  
        for uid in uids:
            self.send(text, from_uid, uid)
        if not uids: res = False 
        return json.dumps(res,default=pymongo.json_util.default) 
    
    @_cp.expose 
    def destroy_msg(self,msgid):
        _cp.response.headers['Content-Type'] = 'application/json'
        res = True 
        try: 
            msgid = _id(msgid)
            msg = self.db.msgs.find_one({'_id':msgid},{'tid':1})
            tid = msg['tid']
            self.db.threads.update({'_id':tid}, {'$inc':{'msg_count':-1}})
            self.db.msgs.remove({'_id':msgid})
        except:
            res = False
        return json.dumps(res)
    
    #调用客户个性化解释分组标签下的客户uid    
    def group_uids(self,gid):
        return set()     
    
    def parse_ids(self,value):
        res = value.split(',')
        for i in range(len(res)):
            res[i] = res[i].strip()
            if res[i]=='': del res[i]
        return res